package com.zw.cloud.common.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.management.ManagementFactory;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Random;

@Slf4j
public class IdUtils {

    private static final long workerId;
    private static final long datacenterId;

    static {
        datacenterId = getDatacenterId(31L);
        workerId = getMaxWorkerId(datacenterId,31L);
    }


    /**
     * 获取 maxWorkerId
     */
    public static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
        StringBuilder mpid = new StringBuilder();
        mpid.append(datacenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (StringUtils.isNotBlank(name)) {
            mpid.append(name.split("@")[0]);
        }
        return (long)(mpid.toString().hashCode() & '\uffff') % (maxWorkerId + 1L);
    }

    /**
     * 获取 datacenterId
     */
    public static long getDatacenterId(long maxDatacenterId) {
        long id = 0L;

        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                if (null != mac) {
                    id = (255L & (long)mac[mac.length - 2] | 65280L & (long)mac[mac.length - 1] << 8) >> 6;
                    id %= maxDatacenterId + 1L;
                }
            }
        } catch (Exception var7) {
            log.warn(" getDatacenterId: " + var7.getMessage());
        }

        return id;
    }

    public static long nextId() {
        Snowflake snowflake = IdUtil.getSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(nextId());
        }
    }
}
